package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * ClassName: OrderTask
 * Package: com.sky.task
 * Description:
 *
 * @Author zhangdingye
 * @Create 2025/4/2 下午4:14
 * @Version 1.0
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 处理支付超时订单
     */
    // 每分钟检查一次
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrder() {
        log.info("处理支付超时订单:{}", LocalDateTime.now());

        LocalDateTime timeOutTime = LocalDateTime.now().plusMinutes(-15);

        // select * from orders where status = 1 and order_time < (当前时间 - 15分钟)
        List<Orders> orders = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, timeOutTime);
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                // 更新订单状态为“已取消”并且更新取消原因
                Orders ordersDB = Orders.builder()
                        .id(order.getId())
                        .status(Orders.CANCELLED)
                        .cancelReason("订单超时，自动取消")
                        .cancelTime(LocalDateTime.now())
                        .build();
                orderMapper.update(ordersDB);
            }
        }
    }


    /**
     * 处理“派送中”状态的订单
     */
    // 每天凌晨1点，处理“派送中”状态的订单
    @Scheduled(cron = "0 0 1 * * ? ")
//    @Scheduled(cron = "1/5 * * * * ?")
    public void processDeliveryOrder() {
        log.info("处理“派送中”状态的订单:{}", LocalDateTime.now());

        LocalDateTime timeOutTime = LocalDateTime.now().plusMinutes(-60);

        List<Orders> orders = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, timeOutTime);
        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                // 更新订单状态为“已完成”
                Orders ordersDB = Orders.builder()
                        .id(order.getId())
                        .status(Orders.COMPLETED)
                        .deliveryTime(LocalDateTime.now())
                        .build();
                orderMapper.update(ordersDB);
            }
        }
    }
}
